package com.meteor.service.impl;

import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.meteor.api.feign.system.SystemFeign;
import com.meteor.api.feign.system.dto.SysMerchantDTO;
import com.meteor.convert.InvitationConvert;
import com.meteor.convert.InvitationRemarkConvert;
import com.meteor.entity.Invitation;
import com.meteor.entity.InvitationRemark;
import com.meteor.framework.common.base.ResponseData;
import com.meteor.framework.common.constant.Constant;
import com.meteor.framework.common.enums.UserAdminEnum;
import com.meteor.framework.common.exception.ServerException;
import com.meteor.framework.common.utils.PageResult;
import com.meteor.framework.mybatis.service.impl.BaseServiceImpl;
import com.meteor.framework.security.user.SecurityUser;
import com.meteor.mapper.InvitationMapper;
import com.meteor.mapper.InvitationRemarkMapper;
import com.meteor.query.InvitationQuery;
import com.meteor.query.InvitationRemarkQuery;
import com.meteor.query.OrgAndCommunityQuery;
import com.meteor.service.CommunityService;
import com.meteor.service.InvitationRemarkService;
import com.meteor.service.InvitationService;
import com.meteor.vo.CommunityVO;
import com.meteor.vo.InvitationRemarkVO;
import com.meteor.vo.InvitationVO;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author lynn
 * @date 2024/1/22
 */


@Service
@AllArgsConstructor
public class InvitationRemarkServiceImpl extends BaseServiceImpl<InvitationRemarkMapper, InvitationRemark> implements InvitationRemarkService {

    private final SystemFeign systemFeign;

    private final CommunityService communityService;

    @Override
    public void save(InvitationRemarkVO vo) {
        InvitationRemark  entity= InvitationRemarkConvert.INSTANCE.convert(vo);

        if(!SecurityUser.getUser().getUsername().equalsIgnoreCase(UserAdminEnum.ADMIN.getValue())){

            if(ObjectUtils.isEmpty(vo.getMerchantId())){
                entity.setMerchantId(SecurityUser.getUser().getMerchantId());
            }

            /*if(ObjectUtils.isEmpty(vo.getCommunityId())){
                OrgAndCommunityQuery query = new OrgAndCommunityQuery();
                query.setOrgId(vo.getOrgId());
                List<CommunityVO> communityVOS = communityService.orgCommunity(query);
                if(ObjectUtils.isEmpty(communityVOS)){
                    throw new ServerException("该机构下没有小区");
                }
                entity.setCommunityId(communityVOS.get(0).getId());
            }*/

            if(ObjectUtils.isEmpty(vo.getOrgId())){
                entity.setOrgId(SecurityUser.getUser().getOrgId());
            }
        }else{

            if(ObjectUtils.isEmpty(vo.getOrgId())) {
                throw new ServerException("请选择机构");
            }
            ResponseData responseData = JSON.parseObject(systemFeign.orgMerchant(vo.getOrgId()),ResponseData.class);
            if(!ObjectUtils.isEmpty(responseData.getData())){
                SysMerchantDTO sysMerchantDTO = JSON.parseObject(responseData.getData().toString(),SysMerchantDTO.class);
                entity.setMerchantId(sysMerchantDTO.getId());
            }
            entity.setOrgId(vo.getOrgId());
            /*if(ObjectUtils.isEmpty(vo.getMerchantId())) {
                throw new ServerException("请选择商户");
            }*/
        }

        if(!ObjectUtils.isEmpty(vo.getImagesUrl())){
            entity.setUrl(JSON.toJSONString(vo.getImagesUrl()));
        }





//        entity.setMerchantId(SecurityUser.getUser().getMerchantId());
//        entity.setOrgId(SecurityUser.getUser().getOrgId());

        baseMapper.insert(entity);
    }

    @Override
    public void update(InvitationRemarkVO vo) {
        InvitationRemark invitationRemark = InvitationRemarkConvert.INSTANCE.convert(vo);
        if (ObjectUtils.isEmpty(invitationRemark.getId())) {
            throw new ServerException("修改失败，id为空");
        }
        baseMapper.updateById(invitationRemark);

    }

    @Override
    public InvitationRemarkVO getInvitationRemark(String id) {
        return InvitationRemarkConvert.INSTANCE.convert(baseMapper.selectById(id));
    }

    @Override
    public List<InvitationRemarkVO> getInvitationRemarkVOList(InvitationRemarkQuery query) {

//        LambdaQueryWrapper<InvitationRemark> wrapper = new LambdaQueryWrapper<InvitationRemark>();
//        wrapper.eq(InvitationRemark::getInvitationId, query.getInvitationId());
        // 查询参数
        Map<String, Object> params = getParams(query);
        List<InvitationRemarkVO> invitationRemarkVOS = baseMapper.getList(params);

        if(!ObjectUtils.isEmpty(invitationRemarkVOS)){
            List<String> remarkIds = invitationRemarkVOS.stream().map(t->t.getId()).collect(Collectors.toList());
            List<InvitationRemarkVO> invitationRemarkVOList = baseMapper.getInvitationRemarkVOList(remarkIds);
            Map<String, List<InvitationRemarkVO>> remarkMap = invitationRemarkVOList.stream().collect(Collectors.groupingBy(InvitationRemarkVO::getParentId));
            invitationRemarkVOS.stream().forEach(t->{
                if(!ObjectUtils.isEmpty(remarkMap.get(t.getId()))){
                    List<InvitationRemarkVO> remarkVOList = remarkMap.get(t.getId());
                    remarkVOList.stream().forEach(o->{
                        o.setParentUserName(t.getCreatedUserName());
                    });
                    t.setChildren(remarkVOList);
                }
            });
        }

        return invitationRemarkVOS;
    }

    @Override
    public PageResult<InvitationRemarkVO> pageInvitationRemarkVO(InvitationRemarkQuery query) {


        // 查询参数
        Map<String, Object> params = getParams(query);

        // 分页查询
        IPage<InvitationRemark> page = getPage(query);
        params.put(Constant.PAGE, page);

        // 数据列表
        List<InvitationRemarkVO> list = baseMapper.getList(params);



        return new PageResult<>(list, page.getTotal());


//        IPage<Malfunction> page = baseMapper.selectPage(getPage(query), getWrapper(query));
//
//        return new PageResult<MalfunctionVO>(MalfunctionConvert.INSTANCE.convertList(page.getRecords()), page.getTotal());

    }

    @Override
    public void delete(String id) {
        removeById(id);
    }

    @Override
    public PageResult<InvitationRemarkVO> miniPage(InvitationRemarkQuery query) {
        Map<String, Object> params = getNoAuthParams(query);


        // 分页查询
        IPage<InvitationRemark> page = getPage(query);
        params.put(Constant.PAGE, page);

        // 数据列表
        List<InvitationRemarkVO> list = baseMapper.getList(params);

        return new PageResult<>(list, page.getTotal());
    }


    private Map<String, Object> getParams(InvitationRemarkQuery query) {
        Map<String, Object> params = new HashMap<>();
        params.put("content", query.getContent());
        params.put("orgId", query.getOrgId());
        params.put("invitationId", query.getInvitationId());


        // 数据权限
        params.put(Constant.DATA_SCOPE, getDataScope("t1", null,"pf_invitation_remark"));

        return params;
    }

    private Map<String, Object> getNoAuthParams(InvitationRemarkQuery query) {
        Map<String, Object> params = new HashMap<>();
        params.put("content", query.getContent());
        params.put("orgId", query.getOrgId());
        params.put("invitationId", query.getInvitationId());


        return params;
    }

    private Wrapper<InvitationRemark> getWrapper(InvitationRemarkQuery query){
        LambdaQueryWrapper<InvitationRemark> wrapper = new LambdaQueryWrapper<>();
        wrapper.like(StrUtil.isNotBlank(query.getContent()), InvitationRemark::getRemarkContent, query.getContent());
        wrapper.like(StrUtil.isNotBlank(query.getInvitationId()), InvitationRemark::getInvitationId, query.getInvitationId());
        // 数据权限
        dataScopeWrapper(wrapper);

        return wrapper;
    }

}
